package co.fitstart.weapp.api.web.controller.course;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.round.CourseRoundFeedback;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.course.schedule.StudentSigninRecord;
import co.fitstart.entity.courseware.fitnessgroup.Courseware;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CourseScheduleService;
import co.fitstart.weapp.api.service.CourseSigninService;
import co.fitstart.weapp.api.service.CoursewareService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/profile")
public class CourseController {

    private static final Logger logger = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CourseScheduleService courseScheduleService;

    @Autowired
    private CoursewareService coursewareService;
    
    @Autowired
    private CourseSigninService courseSigninService;

    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/courses", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult list(@RequestParam("unionid") String unionid) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            
            if(!user.isStudent()) {
                httpResult.success().message("暂无课程");
            } else {
                Student student = userService.getStudent(user);
                
                List<Map<String, Object>> availableCourseRounds = courseRoundService.listAvailable(student);
                List<CourseRound> unavailableCourseRounds = courseRoundService.listUnavailable(student);
                List<CourseRound> onlineRounds = courseRoundService.listOnline(student);
                
                httpResult.success().message("获取数据成功")
                                    .data("appointAvailableCourseRounds", availableCourseRounds)
                                    .data("appointUnavailableCourseRounds", unavailableCourseRounds)
                                    .data("onlineRounds", onlineRounds);
            }
        } catch (Exception e) {
            logger.error("listCourseRound() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/courses/{courseId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult detail(@RequestParam("unionid") String unionid, 
                             @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("courseRound", courseRound)
                                .data("couldAppoint", courseRoundService.couldAppoint(courseRound))
                                .data("experience", courseRound.getCourse().isExperience())
                                .data("needTarget", courseRoundService.needTargetData(courseRound))
                                .data("give", courseRound.getCourse().isGive());
            
            if(courseRound.getFitnessGroup() != null && !courseRound.getCourseType().isOnline()) {
                int plannedCourse = coursewareService.getMaxFinishedCourseCourseware(courseRound);
                int plannedWeekly = coursewareService.getMaxFinishedWeeklyPlan(courseRound);
                
                httpResult.data("plannedCourse", plannedCourse)
                          .data("restCourse", (courseRound.getCourseType().isIndividual() ? courseRound.getCourseAmount() : courseRound.getFitnessGroup().getHours()) - plannedCourse)
                          .data("plannedWeekly", plannedWeekly)
                          .data("restWeekly", courseRound.getFitnessGroup().getWeeks() - plannedWeekly);
            }
                                
            
            if(courseRound.getCourseType().isGroup()) {
                httpResult.data("schedules", courseRound.getSchedules());
            }
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getCourseRoundDetail() error", e);
            httpResult.fail("500").message("加载数据失败");
        }

        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/courses/{courseId}/schedules", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult schedules(@RequestParam("unionid") String unionid, 
                                @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("schedules", courseRoundService.listCourseSchedule(courseRound));
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("listCourseSchedule() error", e);
            httpResult.fail("500").message("加载数据失败");
        }

        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param scheduleId
     * @return
     */
    @RequestMapping(value = "/course-schedules/{scheduleId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult schedule(@RequestParam("unionid") String unionid, 
                               @PathVariable("scheduleId") Long scheduleId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseSchedule courseSchedule = courseScheduleService.load(scheduleId);
            
            courseRoundService.validate(student, courseSchedule);
            
            if(courseSchedule.getContent() == null) {
                coursewareService.initlizeContent(courseSchedule);
            }
            
            StudentSigninRecord studentSigninRecord = courseSigninService.loadSigninRecord(courseSchedule);
            
            httpResult.success().message("获取数据成功")
                                .data("courseSchedule", courseSchedule)
                                .data("courseName", courseSchedule.getCourse().getName())
                                .data("coachAvatar", courseSchedule.getCoach().getProfile() == null ? null : courseSchedule.getCoach().getProfile().getAvatar())
                                .data("couldEdit", courseSchedule.couldEdit())
                                .data("couldCancel", courseSchedule.getCourseType().supportAppointment() && courseSchedule.couldCancel())
                                .data("couldSignin", courseSchedule.couldSignin())
                                .data("signinExpiry", courseSchedule.expiry())
                                .data("roundStatus", courseSchedule.getCourseRound().getCourseStatus().getAlias())
                                .data("scheduleStatus", courseSchedule.getScheduleStatus().getAlias())
                                .data("hasSigninRecord", studentSigninRecord != null ? true : false)
                                .data("give", courseSchedule.getCourse().isGive());
            
            if(courseSchedule.getCourseRound().getCourseType().isYear() || (courseSchedule.getCourseRound().getCourseType().isIndividual() && !courseSchedule.getCourse().isExperience())) {
                int session = coursewareService.getSession(courseSchedule);
                List<Courseware> coursewares = coursewareService.listGeneratedCourseware(courseSchedule);
                
                httpResult.data("session", session)
                          .data("coursewares", coursewares);
            }
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("schedule() error:", e); 
            httpResult.fail("500").message("加载数据失败");
        }

        return httpResult;
    }

    /**
     * 课程吐槽
     * @param unionid
     * @param courseRoundId
     * @param feedback
     * @return
     */
    @RequestMapping(value = "/courses/{courseId}/feedback", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult feedback(@RequestParam("unionid") String unionid, 
                               @PathVariable("courseId") Long courseRoundId,
                               @RequestBody CourseRoundFeedback feedback) {
        HttpResult httpResult = new HttpResult();
        
        try {
            if(StringUtils.isBlank(feedback.getDescription())) {
                httpResult.fail("500").message("吐槽内容不能为空");
            } else {
                User user = userService.load(unionid);
                Student student = userService.getStudent(user);
                CourseRound courseRound = courseRoundService.load(courseRoundId);
                
                courseRoundService.validate(student, courseRound);
                
                courseRoundService.feedback(courseRound, feedback);
                
                httpResult.success().message("吐槽成功");
            }
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("feedback() error", e);
            httpResult.fail("500").message("吐槽失败");
        }

        return httpResult;
    }
}
